package cn.wolfcode.wolf2w.resolver;


import cn.wolfcode.wolf2w.annotation.UserParam;
import cn.wolfcode.wolf2w.cache.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.domain.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 * 能将请求映射方法形式参数中UserInfo对象转换成当前登录用户对象
 */
public class UserInfoArgumentResolver implements HandlerMethodArgumentResolver {
    //表示当前解析器解析那种类型参数
    //返回值boolean类型 true表示支持解析档期啊你的类型  false表示不支持
    @Autowired
    private IUserInfoRedisService userInfoRedisService;
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.getParameterType() == UserInfo.class &&
                methodParameter.hasParameterAnnotation(UserParam.class);
    }
    //执行参数逻辑 并注入参数中
    //执行前提 必须满足supportsPramete方法范湖itrue
    public Object resolveArgument(MethodParameter methodParameter,
                                  ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest,
                                  WebDataBinderFactory webDataBinderFactory) throws Exception {
        //获取当前登录用户
        HttpServletRequest req = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        String token = req.getHeader("token");
        //返回值就是请求映射的方法声明形式参数什么的userinfo对象的值
        //返回当前登录用户对象
        return userInfoRedisService.getUserByToken(token);
    }
}
